<script setup>
import {computed, ref} from "vue";
import { useRouter, useRoute } from "vue-router";
import {ElLoading, ElMessage} from "element-plus";
import {http} from "@/api";
import UploadImage from "@/components/UploadImage.vue";
const apiKey = 'goods'
const router = useRouter()
const route = useRoute()
const id = route.params.id
const copyId = route.query.copyId
const categoryList = ref([])
const areaList = computed(() => {
  return categoryList.value.find(item => item.id === formData.value.category_id)?.areas || []
})
const serverList = computed(() => {
  return areaList.value.find(item => item.id === formData.value.area_id)?.serverList || []
})
http.category.list().then(res => {
  categoryList.value = res.data
})
const formData = ref({
  id: undefined,
  name: '',
  image_desc: '',
  desc: '',
  category_id: undefined,
  server_id: undefined,
  price: undefined,
  publish_time: '',
  status: 1,
  condition: {

  }
})
const rules = ref({
  name: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  category_id: [
    { required: true, message: '请选择', trigger: 'blur' },
  ],
  area_id: [
    { required: true, message: '请选择', trigger: 'blur' },
  ],
  price: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  image: [
    { required: true, message: '请上传', trigger: 'blur' },
  ],
})
const formRef =  ref(null)
const tags = ref([])
if (id) {
  // 获取详情
  http[apiKey].read(id).then(async res => {
    let condition = {}
    try {
      condition = res.data.condition ? JSON.parse(res.data.condition) : []
    }
    catch (e) {
      console.log(e)
    }
    // 获取分类条件
    let conditionRes = await http.tag.list({
      category_id: res.data.category_id,
    })
    let conditionMap = {}
    tags.value = conditionRes.data.map(el => {
      return {
        ...el,
        children: el.children.map(el2 => {
          return {
            ...el2,
            conditions: el2.conditions.map(el3 => {
              conditionMap[el3.field_key] = ''
              return {
                ...el3,
                option: JSON.parse(el3.option)
              }
            })
          }
        })
      }
    })
    formData.value = {
      ...res.data,
      condition: {
        ...conditionMap,
        ...condition,
      }
    }
  })
}

const changeCategory = async (val) => {
  let conditionRes = await http.tag.list({
    category_id: val,
  })
  let conditionMap = {}
  tags.value = conditionRes.data.map(el => {
    return {
      ...el,
      children: el.children.map(el2 => {
        return {
          ...el2,
          conditions: el2.conditions.map(el3 => {
            conditionMap[el3.field_key] = ''
            return {
              ...el3,
              option: JSON.parse(el3.option)
            }
          })
        }
      })
    }
  })
  formData.value = {
    ...formData.value,
    condition: {
      ...conditionMap
    }
  }
}
const cancel = () => {
  router.back()
}
const confirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const loadingInstance = ElLoading.service()
      if (id) {
        // 编辑
        http[apiKey].update({
          ...formData.value,
          id,
          condition: JSON.stringify(formData.value.condition)
        }).then(res => {
          ElMessage.success('编辑成功')
          router.back()
        }).finally(() => {
          loadingInstance.close()
        })
      } else {
        // 新增
        http[apiKey].create({
          ...formData.value,
          condition: JSON.stringify(formData.value.condition)
        }).then(res => {
          ElMessage.success('新增成功')
          router.back()
        }).finally(() => {
          loadingInstance.close()
        })
      }
    } else {
      console.log('error submit!!')
      return false
    }
  })
}
</script>

<template>
  <PageMain :title="id ? '编辑' :'新增'">
    <div class="form-content f-c ">
      <el-tabs type="border-card" class="demo-tabs">
        <el-tab-pane label="基本信息">
          <el-form ref="formRef" style="width: 700px" :model="formData" :rules="rules" label-position="top" >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="所属游戏" prop="category_id">
                  <el-select v-model="formData.category_id" clearable :disabled="formData.id" @change="changeCategory">
                    <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属大区" prop="area_id">
                  <el-select v-model="formData.area_id" clearable>
                    <el-option v-for="item in areaList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属服务" prop="server_id">
                  <el-select v-model="formData.server_id" clearable>
                    <el-option v-for="item in serverList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="价格" prop="price">
                  <el-input clearable v-model="formData.price"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="图片" style="width: 100%" prop="image">
                  <UploadImage v-model:image="formData.image" :size="99"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="描述" prop="desc">
                  <el-input clearable v-model="formData.desc" type="textarea" :rows="5"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="上架状态">
                  <el-switch :active-value="1" :inactive-value="0" v-model="formData.status"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="游戏截图">
          <upload-image v-model:image="formData.image_desc" :size="999999"/>
        </el-tab-pane>
        <el-tab-pane v-for="tag in tags" :label="tag.name">
          <div v-for="tag2 in tag.children">
            <div class="more-tag" >
              <div class="tag"></div>
              <div class="tag-name">{{ tag2.name }}</div>
            </div>
            <el-row :gutter="16">
              <template v-for="item in tag2.conditions">
                <el-col :span="12" v-if="item.field_type === 'checkbox' || item.field_type === 'radio'">
                  <el-form-item :label="item.field_name">
                    <el-select v-model="formData.condition[item.field_key]" clearable :multiple="item.field_type === 'checkbox'">
                      <el-option v-for="option in item.option" :key="option.value" :label="option.label" :value="option.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="item.field_type === 'number' || item.field_type === 'text'">
                  <el-form-item :label="item.field_name">
                    <el-input v-model="formData.condition[item.field_key]" clearable>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="item.field_type === 'image'">
                  <el-form-item label-position="top">
                    <check-image v-model:image="formData.condition[item.field_key]" :option="item.option" />
                  </el-form-item>
                </el-col>
              </template>
            </el-row>

          </div>
        </el-tab-pane>
      </el-tabs>
      <div class="form-box form-box2">
      </div>
      <div class="form-button f-s">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </div>
    </div>
  </PageMain>
</template>
<style lang="scss">
.more-tag {
  display: flex;
  align-items: center;
  line-height: 24px;
  height: 24px;
  color: #344356;
  font-size: 18px;
  font-weight: 700;
  margin: 10px 0;
  .tag {
    display: inline-block;
    height: 18px;
    background: #5468ff;
    width: 4px;
    border-radius: 4px;
    margin-right: 10px;
  }
  .tag-name {
    color: #344356;
  }
}

</style>